package com.yexiao.cofe.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author lkl
 * @since 2025/3/28
 */
@Aspect
@Slf4j
@Component
public class ReqAspect {

    @Pointcut(value = "execution(public * com.yexiao.cofe.business.controller.*.*(..))")
    public void pointCut() {}

    // 拦截所有请求并获取请求对象
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        long start = System.currentTimeMillis();
        String requestURI = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();
        log.info("请求路径：{}， 请求ip：{}", requestURI, remoteAddr);

        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();
        log.info("请求耗时：{}ms", end - start);

        return result;
    }
}
